package com.health.user.controller;


import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.health.api.model.hospital.GetHospitalInfoRequest;
import com.health.api.model.hospital.HospitalVO;
import com.health.api.model.transporter.TransporterRegisterRequest;
import com.health.common.common.BaseResponse;
import com.health.common.common.ErrorCode;
import com.health.common.common.ResultUtils;
import com.health.common.exception.BusinessException;
import com.health.common.exception.ThrowUtils;
import com.health.common.model.user.LoginUser;
import com.health.common.model.vo.UserKeyVO;
import com.health.user.mapper.HospitalMapper;
import com.health.user.model.dto.doctor.DoctorRegisterRequest;
import com.health.user.model.dto.hospital.HospitalRegisterRequest;
import com.health.api.model.producer.ProducerRegisterRequest;
import com.health.user.model.dto.user.PatientRegisterRequest;
import com.health.user.model.entity.Hospital;
import com.health.user.model.entity.User;
import com.health.user.model.vo.LoginUserVO;
import com.health.user.model.vo.UserVO;
import com.health.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.fisco.bcos.sdk.v3.codec.ContractCodecException;
import org.fisco.bcos.sdk.v3.transaction.model.exception.TransactionBaseException;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 用户接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/users")
@Tag(name = "用户接口")
@Slf4j
@CrossOrigin
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private HospitalMapper hospitalMapper;

    /**
     * 患者注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/patientRegister")
    @Operation(summary = "用户注册")
    public BaseResponse<Long> patientRegister(@RequestBody @Valid PatientRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = userService.patientRegister(userRegisterRequest);
        return ResultUtils.success(result);
    }

    /**
     * 根据用户名和密码获取用户信息
     * @return
     */
    @GetMapping(value = "/info",produces = {"application/json"})
    @Operation(summary = "根据用户名和密码获取用户信息")
    public LoginUser getUserInfoByUserAccountAndPassword(@RequestParam String userAccount, @RequestParam String userPassword,@RequestParam  Integer userRole) {
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginUser loginUser = userService.getUserInfoByUserAccountAndPassword(userAccount,userPassword,userRole);
        return loginUser;
    }



    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @Operation(summary = "用户注销")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    @Operation(summary = "获取当前登录用户")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        return ResultUtils.success(userService.getLoginUserVO(request));
    }



    /**
     * 获取医院用户信息
     */
    @PostMapping("/getHospitalInfo")
    @Operation(summary = "获取医院用户信息")
    public HospitalVO getHospitalInfo(@RequestBody GetHospitalInfoRequest getHospitalInfoRequest) {
        if (getHospitalInfoRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long hospitalId = getHospitalInfoRequest.getHospitalId();
        String hospitalAddress = getHospitalInfoRequest.getHospitalAddress();
        String hospitalAccount = getHospitalInfoRequest.getHospitalAccount();

        QueryWrapper<Hospital> queryWrapper = new QueryWrapper<>();
        if (hospitalId!= null){
            queryWrapper.eq("id",hospitalId);
        }
        if (StringUtils.isNotBlank(hospitalAccount)){
            queryWrapper.eq("hospital_account",hospitalAccount);
        }
        if (StringUtils.isNotBlank(hospitalAddress)){
            queryWrapper.eq("hospital_address",hospitalAddress);
        }
        Hospital hospital = hospitalMapper.selectOne(queryWrapper);
        if (hospital == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        HospitalVO hospitalVO = new HospitalVO();
        BeanUtils.copyProperties(hospital,hospitalVO);
        return  hospitalVO;
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @Operation(summary = "根据 id 获取用户（仅管理员）")
    public BaseResponse<User> getUserById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    @Operation(summary = "根据 id 获取包装类")
    public BaseResponse<UserVO> getUserVOById(long id, HttpServletRequest request) {
        BaseResponse<User> response = getUserById(id, request);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 生成自己的公私钥对
     */
    @GetMapping("/generateKey")
    @Operation(summary = "生成自己的公私钥对")
    public BaseResponse<UserKeyVO> generateKey(HttpServletRequest request) throws TransactionBaseException, ContractCodecException {
        UserKeyVO keyPair = userService.generateKey(request);
        return ResultUtils.success(keyPair);
    }

    /**
     * 医院注册
     *
     */
    @PostMapping("/hospitalRegister")
    @Operation(summary = "医院注册")
    public BaseResponse<Long> hospitalRegister(@RequestBody @Valid HospitalRegisterRequest hospitalRegisterRequest) {
        if (hospitalRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = userService.hospitalRegister(hospitalRegisterRequest);
        return ResultUtils.success(result);
    }

    /**
     * 医生注册
     */
    @PostMapping("/doctorRegister")
    @SaCheckRole("hospital")
    @Operation(summary = "医生注册")
    public BaseResponse<UserKeyVO> doctorRegister(@RequestBody @Valid DoctorRegisterRequest doctorRegisterRequest) throws TransactionBaseException, ContractCodecException {
        if (doctorRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserKeyVO result = userService.doctorRegister(doctorRegisterRequest);
        return ResultUtils.success(result);
    }

    @GetMapping("/roleList")
    @Operation(summary = "获取权限列表")
    public List<String> getRoleList(Long loginId) {
        return userService.getRoleList(loginId);
    }

    /**
     * 生产商用户注册
     */
    @PostMapping("/producerRegister")
    @Operation(summary = "生产商用户注册")
    public BaseResponse<Long> producerRegister(@RequestBody @Valid ProducerRegisterRequest producerRegisterRequest) {
        if (producerRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long  userId = userService.producerRegister(producerRegisterRequest);
        return ResultUtils.success(userId);
    }

    @PostMapping("/transportRegister")
    @Operation(summary = "运输商用户注册")
    public BaseResponse<Long> transportRegister(@RequestBody @Valid TransporterRegisterRequest transportRegisterRequest) {
        return ResultUtils.success(userService.transportRegister(transportRegisterRequest));
    }



}
